<!-- 活动历程 -->
<template>
  <div id="course">
    <div class="search">
      <myForm v-bind="formConfig" v-model:formData="formData">
        <template #header>
          <Title>
            <template #title> 搜索公益活动 </template>
          </Title>
        </template>
        <template #footer>
          <div class="footer">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
        </template>
      </myForm>
    </div>
    <div class="table">
      <myTable
        v-bind="tableConfig"
        v-model:pageList="pageList"
        :tableData="tableData"
      >
        <template #header>
          <Title>
            <template #title> 公益活动数据列表 </template>
            <template #right>
              <el-button type="warning" @click="addActivities"
                >新增活动</el-button
              >
            </template>
          </Title>
        </template>
        <template #time="scope">
          {{ dateFromatUTC(scope.row.time) }}
        </template>
        <template #author="scope">
          <template v-if="scope.row.author">
            {{ scope.row.author?.name }}
          </template>
          <template v-else-if="scope.row.author === null">
            该管理员已注销
          </template>
        </template>
        <template #nowTime="scope">
          {{ dateFromatStamp(scope.row.startTime) }} -
          {{ dateFromatStamp(scope.row.endTime) }}
        </template>
        <template #operation="scope">
          <el-button
            type="primary"
            :icon="Edit"
            circle
            @click="updateActivities(scope.row)"
          />
          <el-button
            type="danger"
            :icon="Delete"
            circle
            @click="handleDelete(scope.row._id)"
          />
        </template>
      </myTable>
    </div>

    <!-- 提示内容 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isShowContent ? '修改活动信息' : '新增活动'"
      width="30%"
      destroy-on-close
      draggable
    >
      <!-- <myForm v-bind="formConfig2" v-model:formData="formData2"></myForm> -->
      <div class="list">
        <div class="name">活动名称</div>
        <el-input
          type="text"
          placeholder="请输入活动名称"
          v-model="contents.name"
        ></el-input>
      </div>
      <div class="list">
        <div class="name">活动描述</div>
        <el-input
          type="textarea"
          placeholder="请输入活动描述"
          v-model="contents.des"
        ></el-input>
      </div>
      <div class="list">
        <div class="name">活动时间</div>
        <el-date-picker
          type="daterange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          style="width: 100%"
          :disabled="isShowContent"
          v-model="contents.time"
        />
      </div>
      <div class="list">
        <div class="name">活动地点</div>
        <el-select
          class="m-2"
          placeholder="选择城市"
          style="width: 100%"
          :disabled="isShowContent"
          v-model="contents.place"
        >
          <el-option
            v-for="item in cityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <template v-if="!isShowContent">
            <el-button type="primary" @click="addActivityAxios"
              >新增活动</el-button
            >
          </template>
          <template v-else>
            <el-button type="primary" @click="updateActivityAxios"
              >更新活动</el-button
            >
          </template>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue'

import myForm from '@/base-ui/form'
import myTable from '@/base-ui/table'
import { Title } from '@/components/admin/public'

import { formConfig, tableConfig } from '@/views/admin/config/course.config'

import {
  getActivityList,
  addActivity,
  updateActivity,
  deleteActivity,
  searchActivity
} from '@/server/serve/api_activity'

import { dateFromatStamp, dateFromatUTC } from '@/utils/convserTime'

import type { ActivityListDataTypes } from '@/server/serve/api_activity'

import { Delete, Edit } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'

// 表单数据
const nowForm: any = {}
for (const item of formConfig.formItems) {
  nowForm[`${item.field}`] = ''
  if (item.field === 'place') {
    nowForm[`${item.field}`] = '大同'
  }
}
const formData = ref(nowForm)

// 表格数据
const tableData = ref()

// 分页数据
const pageList = ref({
  // 当前页数
  currentPage: 1,
  // 当前页显示数据条数
  pageSize: 10,
  // 条数列表
  pageSizes: [5, 10, 20, 30],
  // 总数
  total: 0
})

// 监听表格数据展示方式，是否为默认 搜索数据
const defaultDataShowType = ref<boolean>(true)

// 数据初始化
const dataInitialization = () => {
  // 基于默认数据
  if (defaultDataShowType.value) {
    getActivityList(
      pageList.value.pageSize,
      (pageList.value.currentPage - 1) * pageList.value.pageSize
    ).then(({ data: activityResult }) => {
      tableData.value = activityResult.data?.activityList
      pageList.value.total = activityResult.data?.allNums!
    })
  }
  // 基于搜索数据
  else {
    const { name, time, place } = formData.value
    const startTime = new Date(time[0]).getTime() || 0
    const endTime = new Date(time[1]).getTime() || 0
    searchActivity(
      name,
      startTime,
      endTime,
      place,
      pageList.value.pageSize,
      (pageList.value.currentPage - 1) * pageList.value.pageSize
    ).then(({ data: activityResult }) => {
      tableData.value = activityResult.data?.activityList
      pageList.value.total = activityResult.data?.allNums!
    })
  }
}

// 监听分页改变
watch(
  pageList,
  () => {
    dataInitialization()
  },
  { immediate: true, deep: true }
)

// 是否弹出对话框
const dialogVisible = ref<boolean>(false)
// 是否回显对话框内容
const isShowContent = ref<boolean>(false)
// 对话框回显内容
const contents = reactive({
  name: '',
  des: '',
  time: [] as Array<any>,
  place: '',
  _id: ''
})
// 对话框城市选择内容
const cityOptions = [
  {
    value: '大同',
    label: '大同'
  },
  {
    value: '北京',
    label: '北京'
  },
  {
    value: '张家界',
    label: '张家界'
  },
  {
    value: '潍坊',
    label: '潍坊'
  },
  {
    value: '重庆',
    label: '重庆'
  },
  {
    value: '成都',
    label: '成都'
  },
  {
    value: '嘉峪关',
    label: '嘉峪关'
  },
  {
    value: '金昌',
    label: '金昌'
  },
  {
    value: '阳泉',
    label: '阳泉'
  },
  {
    value: '张家口',
    label: '张家口'
  },
  {
    value: '兰州',
    label: '兰州'
  }
]

// 新增活动
const addActivities = () => {
  dialogVisible.value = true
  isShowContent.value = false
  contents.name = ''
  contents.des = ''
  contents.place = ''
  contents._id = ''
  contents.time = []
}

// 修改活动
const updateActivities = (item: ActivityListDataTypes) => {
  dialogVisible.value = true
  isShowContent.value = true
  contents.name = item.name
  contents.des = item.des
  contents.place = item.place
  contents._id = item._id
  if (String(item.startTime).length <= 10) {
    contents.time = [
      new Date(item.startTime * 1000),
      new Date(item.endTime * 1000)
    ]
  } else {
    contents.time = [new Date(item.startTime), new Date(item.endTime)]
  }
}

// 添加活动 发送请求
const addActivityAxios = async () => {
  const startTime = new Date(contents.time[0]).getTime()
  const endTime = new Date(contents.time[1]).getTime()
  const { data } = await addActivity(
    contents.name,
    contents.des,
    contents.place,
    startTime,
    endTime
  )
  if (data.code) return ElMessage.warning(data.mes)
  ElMessage.success(data.mes)
  dataInitialization()
  dialogVisible.value = false
  isShowContent.value = false
}

// 更新活动 发送请求
const updateActivityAxios = async () => {
  const { data } = await updateActivity(
    contents._id,
    contents.name,
    contents.des
  )
  if (data.code) return ElMessage.warning(data.mes)
  ElMessage.success(data.mes)
  dataInitialization()
  dialogVisible.value = false
  isShowContent.value = false
}

// 删除活动
/**
 *
 * @param activityID 公益活动ID
 */
const handleDelete = (activityID: string) => {
  ElMessageBox.confirm('确认删除该公益活动吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const { data } = await deleteActivity(activityID)
      if (data.code) return ElMessage.warning(data.mes)
      ElMessage({
        type: 'success',
        message: data.mes
      })
      dataInitialization()
    })
    .catch(() => {
      console.log()
    })
}

// 搜索活动
const handleSearch = () => {
  defaultDataShowType.value = false
  dataInitialization()
}
</script>

<style scoped lang="less">
#course {
  .search {
    padding: 0 20px 10px;
    background-color: #fff;
    border-radius: 16px;
    .footer {
      display: flex;
      justify-content: flex-end;
    }
  }
  .table {
    margin-top: 20px;
    background-color: #fff;
    padding: 20px;
    border-radius: 16px;
  }
  .list {
    display: flex;
    align-items: center;
    margin-top: 20px;
    .name {
      width: 80px;
    }
  }
}
</style>
